package net.oschina.aibinxiao.scheduler;

import net.oschina.aibinxiao.job.HelloJob2;
import net.oschina.aibinxiao.job.HelloJob3;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

public class HelloScheduler3 {
    public static void main(String[] args) throws SchedulerException {
        // 打印当前时间，格式为 yyyy-MM-dd HH:mm:ss
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(date);
        System.out.println("当前时间是：" + dateStr);

        // 创建一个JobDetail实例，将该实例与HelloJob Class绑定  传入自定义参数
        JobDetail jobDetail = JobBuilder.newJob(HelloJob3.class)
                .withIdentity("myjob3")
                .build();

        // 获取距离当前时间的3秒后的时间--->设置为开始时间StartTime
        date.setTime(date.getTime() + 3 * 1000);

        // 获取距离当前时间的7秒后的时间--->设置为开始时间EndTime  一共会执行三次
        Date endDate = new Date();
        endDate.setTime(endDate.getTime() + 7 * 1000);

        // 创建一个Trigger实例，定义该job立即执行，并且每隔两秒执行一次，直到永远
        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withIdentity("mytrigger3", "group3")
                .startAt(date)
                .endAt(endDate)
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                                .withIntervalInSeconds(2)
                                .repeatForever())
                .build();

        // 创建Scheduler实例
        SchedulerFactory sfact = new StdSchedulerFactory();
        Scheduler scheduler = sfact.getScheduler();
        scheduler.start();
        scheduler.scheduleJob(jobDetail, trigger);
    }
}
